#!/bin/bash
set -xeuo pipefail
set -o errexit

curl -XDELETE http://localhost:9200/eryajf-*?pretty 
#策略关联索引时不能删除,所以先删除索引
curl -XDELETE http://localhost:9200/_ilm/policy/eryajf_policy?pretty 
curl -XDELETE http://localhost:9200/_template/template_eryajf?pretty  

#参考 http://www.eryajf.net/5153.html
#1，创建索引策略
curl -XPUT http://localhost:9200/_ilm/policy/eryajf_policy?pretty -H 'Content-Type: application/json' -d'
{
  "policy": {                       
    "phases": {
      "hot": {                      
        "actions": {
              "rollover":{
                  "max_age":"30s"
              }
        }
      },
      "delete": {
        "min_age": "90s",           
        "actions": {
          "delete": {}              
        }
      }
    }
  }
}
'

#2，创建索引模板
curl -XPUT http://localhost:9200/_template/template_eryajf?pretty -H 'Content-Type: application/json' -d'
{
  "index_patterns": ["eryajf*"],                 
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "index.lifecycle.name": "eryajf_policy",      
    "index.lifecycle.rollover_alias": "eryajf"    
  }
}
'

#3，创建索引
curl -XPUT http://localhost:9200/eryajf-1?pretty -H 'Content-Type: application/json' -d'
{
  "aliases": {
    "eryajf": {
      "is_write_index": true
    }
  }
}
'

#4，配置lifecycle检测时间 默认策略轮询时间间隔为十分钟，这里改成10秒，是为了方便观察滚动效果。
curl -XPUT http://localhost:9200/_cluster/settings?pretty -H 'Content-Type: application/json' -d'
{
  "transient": {
    "indices.lifecycle.poll_interval": "10s" 
  }
}
'

sleep 10
curl -XGET http://localhost:9200/eryajf-*/_ilm/explain?pretty

# 5，功能验证
curl -XPUT http://localhost:9200/eryajf/_doc/_bulk?pretty  -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
'

read -p "检查ILM状态"
curl -XGET http://localhost:9200/eryajf-*/_ilm/explain?pretty
echo "没有更新好，在Kibana查下"
# 这里可以核实状态转换等信息
# http://localhost:5601/app/kibana#/management/elasticsearch/index_management/indices

read -p "继续插入数据"
curl -XPUT http://localhost:9200/eryajf/_doc/_bulk?pretty -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
{"index":{}}
{"message":"hello-04"}
{"index":{}}
{"message":"hello-05"}
{"index":{}}
{"message":"hello-06"}
'
curl -XGET http://localhost:9200/eryajf-*/_ilm/explain?pretty

#在别名上查询相当于在这些索引上都查询
curl -XGET "http://elasticsearch:9200/eryajf/_search" -H 'Content-Type: application/json' -d'
{  
  "query": {    
    "match_all": {    

    }  
 }
}'

echo "done."